from bootstrap.microWebSrv import MicroWebSrv, _client, _response
from .drivers import set_speed, ElectroMagneticDriver, pin_assignments
from .states import states
try:
    from typing import Optional
    from shared_types import *
except:
    pass

electro_magnetic_driver: "Optional[ElectroMagneticDriver]" = None


def on_update_functional_configs(httpClient: _client, httpResponse: _response, routeArgs=None):
    """
    处理功能配置项上传，将配置项写入functional-config.json中
    """
    data: "Optional[DeviceFunctionalConfig]" = httpClient.ReadRequestContentAsJSON()
    if data is not None:
        states.save_and_update_functional_configs(data)
        httpResponse.WriteResponseJSONOk({"msg": "success"})
    else:
        httpResponse.WriteResponseJSONError(
            400, f"Cannot update functional configs because data is None.")


def on_get_functional_configs(httpClient: _client, httpResponse: _response, routeArgs=None):
    """
    处理获取功能配置项请求
    """
    cfgs = states.get_functional_configs()
    if cfgs is not None:
        httpResponse.WriteResponseJSONOk(cfgs)
    else:
        httpResponse.WriteResponseJSONError(
            404, f"No functional config exist.")


def on_initialize(httpClient: _client, httpResponse: _response, routeArgs=None):
    """
    处理初始化请求
    """
    data = httpClient.ReadRequestContentAsJSON()
    try:
        if data is not None:
            data: "InitializationData"
            states.control_station_ip = data['control_station_ip']
            httpResponse.WriteResponseJSONOk({"msg": "success"})
        else:
            httpResponse.WriteResponseJSONError(
                400, {"msg": f"cannot deal with initialization data: {data}"})
    except Exception as e:
        httpResponse.WriteResponseJSONError(
            500, {"msg": f"Error occurred {e}, cannot deal with initialization data: {data}"})


def on_set_speed(httpClient: _client, httpResponse: _response, routeArgs=None):
    """
    处理最基本的配置项上传，将配置项写入config.json中
    """
    data = httpClient.ReadRequestContentAsJSON()
    if data is not None and 'speed' in data:
        set_speed(int(data['speed']))
        httpResponse.WriteResponseJSONOk({"msg": "success"})
    else:
        httpResponse.WriteResponseJSONError(
            400, {"msg": f"no data provided, data: {data}"})


def on_set_magnet(httpClient: _client, httpResponse: _response, routeArgs=None):
    """
    处理电磁铁控制
    """
    global electro_magnetic_driver
    data: "ElectroMagnetRequest" = httpClient.ReadRequestContentAsJSON()
    if not electro_magnetic_driver:
        electro_magnetic_driver = ElectroMagneticDriver(
            pin_assignments.get_electromagnet_pins())
    electro_magnetic_driver.action(data['index'], data['state'])
    httpResponse.WriteResponseJSONOk({"msg": "success"})


ROUTES_TRAIN_CONTROL = [
    ("/ctrl/update_functional_configs", "POST", on_update_functional_configs),
    ("/ctrl/get_functional_configs", "GET", on_get_functional_configs),
    ("/ctrl/set_speed", "POST", on_set_speed),
    ("/ctrl/initialize", "POST", on_initialize),
    ("/ctrl/set_magnet", "POST", on_set_magnet),
]
